package top.winshu.common.web.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.winshu.common.exception.WinshuParseException;
import top.winshu.common.util.JsonUtil;
import top.winshu.common.web.context.RequestContext;
import top.winshu.common.web.context.RequestContextUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.StringJoiner;

/**
 * 打印web请求日志
 *
 * @author winshu
 * @since 2021/6/7
 **/
@Aspect
public class WebLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    public WebLogAspect() {
        LOGGER.info(">>>>> 初始化 WebLogAspect");
    }

    // 给controller下定义的所有请求打印日志
    @Pointcut("execution(public * *..controller..*Controller.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        RequestContextUtil.setRequestContext(request, joinPoint);

        LOGGER.debug("========================================== Start ==========================================");
        LOGGER.debug("URL            : {}", request.getRequestURL().toString());
        LOGGER.debug("HTTP Method    : {}", request.getMethod());
        LOGGER.debug("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        LOGGER.debug("IP             : {}", request.getRemoteAddr());
        LOGGER.debug("X-APP-ID       : {}", request.getHeader("X-APP-ID"));
        LOGGER.debug("Request Args   : [{}]", getJsonArgs());
        LOGGER.debug("==========================================  End  ==========================================");
    }

    static String getJsonArgs() {
        RequestContext context = RequestContextUtil.getRequestContext();
        if (context == null) {
            return "";
        }
        StringJoiner jsonArgs = new StringJoiner(",");
        for (Object object : context.getArgs()) {
            if (!(object instanceof Serializable)) {
                continue;
            }
            try {
                jsonArgs.add(JsonUtil.toJson(object));
            } catch (WinshuParseException e) {
                jsonArgs.add("\"*" + object.getClass().getName() + "\"");
            }
        }
        return jsonArgs.toString();
    }
}
